//
//  ALSShareTool.m
//  第三方组件原生的分享
//
//  Created by isenu on 16/9/21.
//  Copyright © 2016年 isenu. All rights reserved.
//

#define KscreenWidth [UIScreen mainScreen].bounds.size.width
#define KscreenHeight [UIScreen mainScreen].bounds.size.height

#import "ALSShareTool.h"
#import "ALSSDK.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import "WeiboSDK.h"

/**
 *  自定义的button
 */
@interface MyButton : UIButton
@property (nonatomic, weak) UIImageView *icon;
@property (nonatomic, weak) UILabel *title;

@end
/**
 *  自定义的view
 */
@interface MyView : UIButton

@property (nonatomic, strong) MyButton *QQFriend;
@property (nonatomic, strong) MyButton *weChatTimeLine;
@property (nonatomic, strong) MyButton *weChatFriend;
@property (nonatomic, strong) MyButton *weibo;
@property (nonatomic, strong) UILabel *viewName;
@property (nonatomic, strong) UIButton *cancleBtn;

@end


/**
 *  遮罩
 */
@interface shadeView : UIView

@end

/**
 *  自定义的VC
 */
@interface MyViewController : UIViewController
@property (weak, nonatomic) shadeView *shadeView;
@end



/**
 *  自定义的ALSShareTool
 */
@interface ALSShareTool ()
@property (nonatomic, strong) UIWindow *window;
@property (weak, nonatomic) MyViewController *viewController;

@property (nonatomic, copy) void(^success)(BOOL success);
@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *subTitle;
@property (nonatomic, strong) NSString *imageName;
@end


@implementation ALSShareTool

static ALSShareTool *shareTool;


+ (instancetype)sharedInstence{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareTool = [[ALSShareTool alloc] init];
    });
    
    return shareTool;
}

- (instancetype)init{

    if (self == [super init]) {
        
    }
    return self;

}
/*
 *分享接口
 */
- (void)ALSShareWebURL:(NSString *)url
                 title:(NSString *)title
              subTitle:(NSString *)subTitle
             imageName:(NSString *)imageName
              finished:(void(^)(BOOL success))finished{
    //保存外部的block块，在合适的地方调用
    self.success = finished;
    //存储分享信息
    self.url = url;
    self.title = title;
    self.subTitle = subTitle;
    self.imageName = imageName;
    //创建window，显示UI
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.windowLevel =UIWindowLevelStatusBar;
    [self.window makeKeyAndVisible];
    MyViewController *viewController = [[MyViewController alloc] init];
    viewController.view.frame = [UIScreen mainScreen].bounds;
    self.window.rootViewController = viewController;
    self.viewController = viewController;
    
    //接受分享按钮的点击通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(share:) name:@"clickShareButton" object:nil];

}
/*
 * 开始分享
 */
- (void)share:(NSNotification *)noti
{

    MyButton *button = noti.userInfo[@"shareType"];

    if (button.tag == WeChatFrind) {

        //判断是否安装微信
        if (![WXApi isWXAppInstalled]) return;
        //不能提示用户，没有安装，可能上架会被拒
//        {
//            [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您还没有安装微信" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil] show];
//            //最好不要执行这句，可能用户这个应用没有安装，但可是去分享到其他应用，引导分享
////            [self hidenWithCompletionBlock:nil];
//            return;
//        }
        //先隐藏掉界面，和友盟分享一样
        [self hidenWithCompletionBlock:nil];
        //吊起微信分享
        [ALSSDK weChatShareWebURL:self.url
                          description:self.subTitle
                           thumbImage:[UIImage imageNamed:self.imageName]
                                title:self.title
                                scene:WXShareSceneSession
                             finished:^(ALSShareResponse *response) {
                                 
                                 //调用外部的block
                                 !self.success?:self.success(response.success);
        }];

    }else if (button.tag == WeChatTimeLine) {

        if (![WXApi isWXAppInstalled]) return;
        [self hidenWithCompletionBlock:nil];
        
        [ALSSDK weChatShareWebURL:self.url
                          description:self.subTitle
                           thumbImage:[UIImage imageNamed:self.imageName]
                                title:self.title
                                scene:WXShareSceneTimeline
                             finished:^(ALSShareResponse *response) {
                                 
                                 !self.success?:self.success(response.success);
        }];

    }else if (button.tag == WeiBo){

        if (![WeiboSDK isWeiboAppInstalled]) return;
        
        
        [self hidenWithCompletionBlock:nil];
        
        UIImage *previewImage = [UIImage imageNamed:self.imageName];
        [ALSSDK weiboShareWebURL:self.url
                               title:self.title
                         description:self.subTitle
                          thumbImage:UIImagePNGRepresentation(previewImage)
                               scene:WeiboShareSceneTimeline
                            finished:^(ALSShareResponse *response) {

                                !self.success?:self.success(response.success);
                                
                            }];

    }else{
        if (![QQApiInterface isQQInstalled]) return;
        
        [self hidenWithCompletionBlock:nil];
        UIImage *previewImage = [UIImage imageNamed:self.imageName];
        [ALSSDK qqShareWebURL:self.url
                      description:self.subTitle
                       thumbImage:UIImagePNGRepresentation(previewImage)
                            title:self.title
                            scene:QQShareSceneSession
                         finished:^(ALSShareResponse *response) {
                             
                             !self.success?:self.success(response.success);
        }];
    }
}
/*
 * 隐藏UI
 */
- (void)hidenWithCompletionBlock:(void(^)())completion {

    dispatch_async(dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.2 animations:^{
            self.viewController.shadeView.alpha = 0;
        } completion:^(BOOL finished) {
            //清除UI
            [self cleanup];
            //调用外部的block块
            !completion?:completion();
        }];
    });
}

- (void)cleanup{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.window removeFromSuperview];
    self.window = nil;
}
- (void)dealloc{
    [self cleanup];
}

@end




/**
 *  自定义的VC
 */
@implementation MyViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    shadeView *shadeview = [[shadeView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:shadeview];
    self.shadeView = shadeview;
}

@end


//遮罩
@implementation shadeView


- (void)layoutSubviews{

    [super layoutSubviews];
    MyView *view = [[MyView alloc] initWithFrame:CGRectMake(0, KscreenHeight - KscreenWidth/4*1.5 - 30 - 40, KscreenWidth, KscreenWidth/4*1.5 + 30 + 40)];
    [self addSubview:view];

}


- (instancetype)initWithFrame:(CGRect)frame{

    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithWhite:0.4 alpha:0.8];
    }
    return self;

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [[ALSShareTool sharedInstence] hidenWithCompletionBlock:nil];
}

@end

/**
 *  自定义的View
 */
@implementation MyView

- (UILabel *)viewName{

    if (!_viewName) {
        _viewName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KscreenWidth, 30)];
        _viewName.textAlignment = NSTextAlignmentCenter;
        _viewName.text = @"分享";
    }
    return _viewName;
}
- (MyButton *)weibo{

    if (!_weibo) {
        _weibo = [self creatShareBtnOfName:@"微博" imageName:@"weibo" index:WeiBo];
    }
    return _weibo;

}

- (MyButton *)weChatFriend{

    if (!_weChatFriend) {
        _weChatFriend = [self creatShareBtnOfName:@"微信好友" imageName:@"weChatFriend" index:WeChatFrind];
    }
    return _weChatFriend;
}

- (MyButton *)weChatTimeLine{

    if (!_weChatTimeLine) {

        _weChatTimeLine = [self creatShareBtnOfName:@"朋友圈" imageName:@"wechat_moment_c" index:WeChatTimeLine];
        
    }
    return _weChatTimeLine;
}

- (MyButton *)QQFriend{

    if (!_QQFriend) {
        _QQFriend = [self creatShareBtnOfName:@"QQ好友" imageName:@"QQFriend" index:qqFriend];
    }
    return _QQFriend;
}

- (MyButton *)creatShareBtnOfName:(NSString *)name imageName:(NSString *)imageName index:(NSInteger)index{

    MyButton *button = [[MyButton alloc] initWithFrame:CGRectMake(KscreenWidth/4 * index, 30, KscreenWidth/4, KscreenWidth/4 * 1.5)];
    button.tag = index;
    button.title.text = name;
    button.icon.image = [UIImage imageNamed:imageName];
    [button addTarget:self action:@selector(clickShareBtn:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (void)clickShareBtn:(UIButton *)button{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"clickShareButton" object:nil userInfo:@{@"shareType":button}];

}


- (UIButton *)cancleBtn{

    if (!_cancleBtn) {
        _cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 40, KscreenWidth, 40)];
        _cancleBtn.backgroundColor = [UIColor whiteColor];
        [_cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_cancleBtn addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancleBtn;

}

- (void)cancle{

    [[ALSShareTool sharedInstence] hidenWithCompletionBlock:nil];
}
- (instancetype)initWithFrame:(CGRect)frame{

    if (self==[super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
        [self addSubview:self.viewName];
        [self addSubview:self.weibo];
        [self addSubview:self.weChatFriend];
        [self addSubview:self.weChatTimeLine];
        [self addSubview:self.QQFriend];
        [self addSubview:self.cancleBtn];
    }
    return self;
}
@end

/**
 自定义的button
 */
@implementation MyButton

- (instancetype)initWithFrame:(CGRect)frame {

    if (self == [super initWithFrame:frame]) {
        
        CGFloat buttonW = self.frame.size.width;
        
        UIImageView *icon = [[UIImageView alloc] init];
//        icon.size = CGSizeMake(self.width * 0.6, self.width * 0.6);
        icon.frame = CGRectMake(0, 0, buttonW * 0.6, buttonW * 0.6);
        
        icon.center = CGPointMake(buttonW * 0.5, buttonW * 0.5);
        [self addSubview:icon];
        self.icon = icon;
        
        UILabel *title = [[UILabel alloc] init];
        title.textAlignment = NSTextAlignmentCenter;
        title.font = [UIFont systemFontOfSize:14];
//        title.size = CGSizeMake(self.width, self.width * 0.5);
        title.frame = CGRectMake(0, 0, buttonW, buttonW * 0.5);
        title.center = CGPointMake(buttonW * 0.5, buttonW*1.10);
        [self addSubview:title];
        self.title = title;
    }
    return self;
}

@end
